package com.amber.proyecto.envia.imagenes.sw.usuario;

import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.amber.proyecto.envia.imagenes.sw.EnviaImagenSW;
import com.amber.proyecto.envia.imagenes.sw.Principal;
import com.amber.proyecto.envia.imagenes.sw.R;
import com.amber.proyecto.envia.imagenes.sw.camara.ObtieneImgCam;
import com.amber.proyecto.envia.imagenes.sw.utils.ImagenParcelable;
import com.amber.proyecto.envia.imagenes.sw.utils.Variables;

public class MuestraInfoUsu extends Activity{
	private ProgressDialog pDialog;
	private ImageView ivImagenInfoUsu;
	private Bundle bundle;
	private String ruta = "http://"+Variables.HOST+"/pags/";
    private String URL = "http://"+Variables.HOST+"/pags/servicios.php";	

	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.muestrainfousu);
		
		bundle = getIntent().getExtras();
		ImagenParcelable imagen = new ImagenParcelable();
		imagen = bundle.getParcelable("datosImagen");
		ivImagenInfoUsu = (ImageView)findViewById(R.id.ivImagenMuestraInfoUsu);
		try{
			new MuestraImagenURL(ivImagenInfoUsu).execute(ruta+imagen.getNombreImagen());
			
			TextView tvCategoria = (TextView)findViewById(R.id.tvCategoriaMuestraInfoUsu);
			TextView tvComentario = (TextView)findViewById(R.id.tvComentarioMuestraInfoUsu);
			RatingBar rbCalifica = (RatingBar)findViewById(R.id.ratingBarMuestraInfoUsu);
			
			tvCategoria.setText(imagen.getNombreCategoria());
			tvComentario.setText(imagen.getComentario());
			rbCalifica.setRating(imagen.getCalificacion());
			
			Button btnAtras = (Button)findViewById(R.id.btnAtrasAgregaCont);
			btnAtras.setOnClickListener(btnAtrasPres);
			
			Button btnInicio = (Button)findViewById(R.id.btnInicioAgregaCont);
			btnInicio.setOnClickListener(btnInicioPres);
			
			Button btnCerrarSes = (Button)findViewById(R.id.btnCerrarSesionAgregaCont);
			btnCerrarSes.setOnClickListener(btnCerrarSesPres);
		}
		catch(Exception err){
			Toast.makeText(MuestraInfoUsu.this, "No se puede recuperar la imagen", Toast.LENGTH_LONG).show();
			Intent intent = new Intent();
    		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra("correoUsuario", bundle.getString("correoUsuario"));
			intent.setClass(MuestraInfoUsu.this, MainActivity.class);
			startActivity(intent);
			finish();
			
		}
		
		
	}
	
	private OnClickListener btnCerrarSesPres = new OnClickListener() {

		public void onClick(View v) {
			Intent intent = new Intent();
    		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.setClass(MuestraInfoUsu.this, Principal.class);
			Variables.inicioSesion = false;
			startActivity(intent);
			finish();			
		}
	};
	
	private OnClickListener btnInicioPres = new OnClickListener() {

		public void onClick(View v) {
			Intent intent = new Intent();
    		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra("correoUsuario", bundle.getString("correoUsuario"));
			intent.setClass(MuestraInfoUsu.this, Principal.class);
			startActivity(intent);
			finish();			
		}
	};
	
	private OnClickListener btnAtrasPres = new OnClickListener() {

		public void onClick(View v) {
			Intent intent = new Intent();
    		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra("correoUsuario", bundle.getString("correoUsuario"));
			Log.i("CorreoUsuario",bundle.getString("correoUsuario"));
			intent.setClass(MuestraInfoUsu.this, MainActivity.class);
			startActivity(intent);
			finish();
		}
	};
	
	protected Dialog onCreateDialog(int id) {
	    switch (id) {
	    case 0:
	        pDialog = new ProgressDialog(this);
	        pDialog.setMessage("Descargando imagen. Espere...");
	        pDialog.setIndeterminate(false);
	        pDialog.setMax(100);
	        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	        pDialog.setCancelable(true);
	        pDialog.show();
	        return pDialog;
	    default:
	        return null;
	    }
	}
	
	
	class MuestraImagenURL extends AsyncTask<String, String, WeakReference<Bitmap>> {
		  private ImageView bmImage;

		  public MuestraImagenURL(ImageView bmImage) {
		      this.bmImage = bmImage;
		  }

		  protected WeakReference<Bitmap> doInBackground(String... urls) {
		      String urldisplay = urls[0];
		      WeakReference<Bitmap> mIcon11 = null;
		      try {
				  BitmapFactory.Options options = new BitmapFactory.Options();
				     options.inSampleSize = 4;
				     options.inPurgeable=true;
				     options.inTempStorage =new byte[32 * 1024]; 
		        InputStream in = new java.net.URL(urldisplay).openStream();
		        InputStream in2 = new java.net.URL(urldisplay).openStream();
		        
		        
		        URL url = new URL(urls[0]);
		        URLConnection conection = url.openConnection();
	            conection.connect();
	            // getting file length
	            int lenghtOfFile = conection.getContentLength();
	            
		        
		        byte data[] = new byte[1024];
		        int count = 0;
	            long total = 0;
	            while ((count = in.read(data)) != -1) {
	                total += count;
	                // publishing the progress....
	                // After this onProgressUpdate will be called
	                publishProgress(""+(int)((total*100)/lenghtOfFile));
	 
	            }
	            
	            mIcon11 = new WeakReference<Bitmap>(BitmapFactory.decodeStream(in2, null, options));
		        in.close();
		        in2.close();
		      } catch (Exception e) {
		          Log.e("Error: ", e.getMessage());
		          e.printStackTrace();
		      }
		      return mIcon11;
		  }

		  protected void onPostExecute(WeakReference<Bitmap> result) {
			  dismissDialog(0);   
		      bmImage.setImageBitmap(result.get());
		  }
		  
		  @Override
		protected void onPreExecute() {

			super.onPreExecute();
			showDialog(0);
	
		}
		  
		  @Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);
			
			pDialog.setProgress(Integer.parseInt(values[0]));			
		}
		  
	}

}
